using System.Text;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using WebAPI;

var builder = WebApplication.CreateBuilder(args);

//数据库链接字符串
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ??
                       throw new InvalidOperationException("Connection string 'DefaultConnection' not found");

//数据库上下文注入 使用pgsql
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString));

//Identity注入，添加数据库上下文  配置认证，授权 存储用户和角色数据
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
// Add services to the container.

builder.Services.AddControllers();

//添加Authentication服务：Cookie 认证
// builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);

//添加jwt验证
builder.Services.AddAuthentication(options => {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters {
            ValidateIssuer = true, //是否验证issuer
            ValidateAudience = true, //是否验证audience
            ValidateLifetime = true, //是否验证token有效期
            ClockSkew = TimeSpan.FromSeconds(30), //时钟偏差 过期时间容错值，解决服务器端时间不同步问题（秒）
            ValidateIssuerSigningKey = true, //是否验证签名
            ValidAudience = JwtConst.Audience, //验证的audience
            ValidIssuer = JwtConst.Issuer, //验证issuer
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey)) //验证签名的密钥
        };
    });

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

//启动authentication中间件
app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();